#include "StdAfx.h"
#include "TcpClient.h"

#include <Network/TcpPacket.h>
#include <Network/TcpPacketDispatcher.h>

#include <boost/bind.hpp>

TcpClient::TcpClient(TcpIoLoop& ioLoop, TcpConnectionEventHandler* eventHandler)
: ioLoop_(ioLoop)
, socketPtr_()
, eventHandler_(eventHandler)
, connection_(NULL)
{
}

TcpClient::~TcpClient(void)
{
}

void TcpClient::Start(std::string& ip, std::string& port)
{
	if( connection_ )
		return ;

	boost::asio::ip::tcp::resolver resolver(ioLoop_.Get());
	boost::asio::ip::tcp::resolver::query query(ip, port);
	boost::asio::ip::tcp::endpoint endpoint = *resolver.resolve(query);
	socketPtr_.reset(new boost::asio::ip::tcp::socket(ioLoop_.Get()));
	socketPtr_->async_connect(endpoint, boost::bind(&TcpClient::OnConnectCompleted, this, boost::asio::placeholders::error));
}

void TcpClient::Stop()
{
	if( connection_ )
	{
		delete connection_;
		connection_ = NULL;
	}
}

void TcpClient::OnConnectCompleted(const boost::system::error_code& error)
{
	if(!error)
	{
		connection_ = new TcpConnection(socketPtr_, eventHandler_);
		connection_->Start();

		eventHandler_->OnConnected(connection_, error.value());
	}
	else
	{
#ifdef _DEBUG
		std::cout << "Connection::OnConnectCompleted(), Error: " << error.message() << "\n";
#endif
		eventHandler_->OnConnected(NULL, error.value());

		socketPtr_->close();
	}
}